<?php
namespace app\api\controller;

use think\Controller;
use think\Db;

class Order extends Controller
{
    /**
     * 保存用户订单信息
     * @return array
     */
    public function saveOrder()
    {
        // 获取POST请求数据
        $postData = $this->request->post();
        
        // 验证必要参数
        if (empty($postData['user_id']) || empty($postData['order_no']) || 
            empty($postData['bank_card']) || empty($postData['product_ids'])) {
            return ['code' => 400, 'msg' => '缺少必要参数'];
        }

        // 将商品ID数组转换为字符串
        $productIdsStr = is_array($postData['product_ids']) ? 
            implode(',', $postData['product_ids']) : $postData['product_ids'];
        
        // 准备插入数据
        $data = [
            'user_id' => $postData['user_id'],
            'order_no' => $postData['order_no'],
            'bank_card' => $postData['bank_card'],
            'product_ids' => $productIdsStr,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        try {
            // 插入数据库
            $result = Db::name('order')->insert($data);
            
            if ($result) {
                return ['code' => 200, 'msg' => '订单保存成功', 'data' => ['order_no' => $postData['order_no']];
            } else {
                return ['code' => 500, 'msg' => '订单保存失败'];
            }
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => '系统错误：' . $e->getMessage()];
        }
    }
}